package com.ibeetl.admin.core.util;

import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.rbac.tree.DictItem;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class DictBuildUtil {
    private DictBuildUtil() {

    }

    public static DictItem buildDictTree(List<CoreDict> list) {
        CoreDict root = new CoreDict();
        root.setId(0L);
        root.setType("");
        root.setName("主菜单");
        DictItem rootDict = new DictItem(root);
        buildTreeNode(rootDict, list);
        return rootDict;
    }
    public static DictItem buildDictTableTree(List<CoreDict> list) {
    	CoreDict root = new CoreDict();
    	root.setId(0L);
    	root.setType("");
    	root.setName("主菜单");
    	DictItem rootDict = new DictItem(root);
    	buildTableTreeNode(rootDict, list);
    	return rootDict;
    }

    private static void buildTreeNode(DictItem parent, List<CoreDict> list) {
        if (parent == null) {
        	return ;
        }

        long id = parent.getId();
        List<CoreDict> dels = new ArrayList<>();
        for (CoreDict sysDict : list) {
            if (sysDict.getParent() == id) {
                DictItem item = new DictItem(sysDict);
                item.setParent(parent);
                dels.add(sysDict);
            }
        }
        list.removeAll(dels);

        if (list.isEmpty()) {
            return;
        }

        sortDict(parent.getChildren());

        for (DictItem child : parent.getChildren()) {
            buildTreeNode(child, list);
        }
    }

    //不使用DictItem里面的children存放子栏目，直接循环取出所有的栏目，用pid识别父栏目，用于treeGrid需要的json格式
    private static List<DictItem> buildTableTreeNode(DictItem parent, List<CoreDict> list) {
    	List<DictItem> dictItemList = new ArrayList<DictItem>();
    	long id = parent.getId();
    	for (CoreDict sysDict : list) {
			DictItem item = new DictItem(sysDict);
			item.setParent(parent);
			dictItemList.add(item);
    	}

    	return dictItemList;
    }

	private static void sortDict(List<DictItem> children) {
		Collections.sort(children, new Comparator<DictItem>() {

			@Override
			public int compare(DictItem o1, DictItem o2) {
				return o1.getSeq().compareTo(o2.getSeq());
			}
			
		});
		
	}

}
